package com.appspot.categoryeditor.controller;

import org.slim3.controller.Controller;
import org.slim3.datastore.Datastore;

import com.appspot.categoryeditor.exception.EntityPropertySizeLimitException;
import com.appspot.categoryeditor.meta.CategoryMeta;
import com.appspot.categoryeditor.model.Category;
import com.appspot.categoryeditor.service.CategoryService;
import com.google.appengine.api.datastore.Transaction;

public abstract class AbstractCategoryController extends Controller {

	protected String userid;
	protected String categoryid;
	protected Category categoryModel;	
	protected CategoryService categoryService = new CategoryService();

	protected final static CategoryMeta CATEGORY_META = CategoryMeta.get();
	
	protected void getParams() {
		userid = asString("userid");
		categoryid = asString("categoryid");
	}
	
	
	protected void getCategoryModel() {
		categoryModel = categoryService.getCategory(
				userid,
				categoryid);
	}
	
	protected void checkContentSize() throws EntityPropertySizeLimitException {
		int contentSize = categoryModel.getContent().getBytes().length;
		if(contentSize > 1024 * 800){
			throw new EntityPropertySizeLimitException(
					"content size is over. limit is 800KB. But the data is " + contentSize + " bytes.");
		}
	}
	
	protected void putCategory() {
		Transaction tx = Datastore.beginTransaction();
		try {
			categoryService.put(tx, categoryModel);
			tx.commit();
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
		}
	}
	

}
